<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple search">
            <el-form ref="query" :model="query" label-width="100px">
              <el-form-item style="margin-bottom:0px" label="名称">
                <i slot="label" class="el-icon-search" style="font-size:20px"></i>
                <el-input v-model="query.value" placeholder="分类名称"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple-light" style="text-align:right">
            <el-button type="primary" @click="queryAsk">查询</el-button>
            <el-button @click="queryReset">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 表格 -->
    <el-card class="box-card">
      <img
        class="watermark"
        v-if="baseApi== 'https://testouhun.wm2177.com'"
        style="right: 0;"
        src="@/assets/watermark.png"
      />

      <el-button type="primary" style="margin-bottom:20px" @click="addList">添加</el-button>
      <el-table
        :data="tableData"
        :default-expand-all="false"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        :header-cell-style="{background:'#eee'}"
        border
        v-loading="loading"
        style="width: 100%;margin-bottom: 20px;"
      >
        <el-table-column align="center" type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="class_name" label="分类名称" width="350"></el-table-column>
        <el-table-column align="center" prop="sort" label="排序"></el-table-column>
        <el-table-column align="center" prop="add_time" label="添加时间"></el-table-column>
        <el-table-column align="center" prop="update_time" label="更新时间"></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleEdite(scope.row)" type="text" size="small">编辑</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="确定删除吗？"
              @onConfirm="handleDel(scope.row)"
            >
              <el-button
                style="margin-left:10px;color:red"
                slot="reference"
                type="text"
                size="small"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="margin-left:50px">
        <el-form-item label="名称" prop="class_name">
          <el-input v-model="form.class_name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="pid">
          <el-select v-model="form.pid" placeholder="请选择分类">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.class_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="subCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  categoryList,
  addCategory,
  editCategory,
  delCategory
} from '@/api/product'
import { upload } from '@/api/system'
import { parseTime } from '@/utils/index'

export default {
  name: 'ProductCategory',
  data() {
    return {
      baseApi: process.env.VUE_APP_BASE_API,
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      // 表数据
      tableData: [],
      // 编辑抽屉
      drawer: false,
      sendDrawer: false,
      direction: 'rtl',
      title: '编辑',
      // 筛选
      query: {
        value: ''
      },
      form: {
        pid: '',
        class_name: '',
        sort: ''
      },
      rules: {
        pid: [{ required: true, message: '请选择分类', trigger: 'blur' }],
        class_name: [
          { required: true, message: '请选输入名称', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '请选输入排序', trigger: 'blur' }]
      },
      // 上传图片
      url: '',
      imageUrl: '',
      postData: {
        token: ''
      },
      options: '',
      loading: false
    }
  },
  mounted() {
    this.getList()
    this.getToken()
  },
  methods: {
    //获取分类列表
    async getList() {
      this.loading = true
      const res = await categoryList({
        page: this.currentPage,
        limit: this.pageSize,
        keywords: this.query.value
      })
      this.loading = false
      this.total = res.count
      this.tableData = res.data
      this.setTime(this.tableData)
      this.options = [
        {
          id: '0',
          class_name: '一级分类'
        }
      ]
      this.options = this.options.concat(res.data)
      console.log(res)
    },
    setTime(data) {
      data.forEach((item) => {
        if (item.children) {
          this.setTime(item.children)
        }
        if (item.add_time == 0) {
          item.add_time = '-'
        } else {
          item.add_time = parseTime(item.add_time, '{y}-{m}-{d} {h}:{i}:{s}')
        }
        if (item.update_time == 0) {
          item.update_time = '-'
        } else {
          item.update_time = parseTime(
            item.update_time,
            '{y}-{m}-{d} {h}:{i}:{s}'
          )
        }
      })
    },
    addList() {
      this.drawer = true
      this.title = '添加'
    },
    // 表格操作
    async handleDel(row) {
      try {
        const res = await delCategory({ id: row.id })
        console.log(res)
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('删除失败')
        console.log(error)
      }
    },
    handleEdite(row) {
      this.drawer = true
      this.title = '编辑'
      console.log(row)
      this.form.sort = row.sort
      this.form.class_name = row.class_name
      this.form.pid = row.pid
      this.form.id = row.id
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current
      this.getList()
    },
    queryAsk() {
      this.currentPage = 1
      this.getList()
    },
    queryReset() {
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.value = ''
      this.resetForm('query')
      this.getList()
    },
    //抽屉
    handleClose(done) {
      this.resetForm('form')
      const form = {
        pid: '',
        class_name: '',
        sort: ''
      }
      this.form = form
      done()
    },
    subCancel() {
      this.resetForm('form')
      const form = {
        pid: '',
        class_name: '',
        sort: ''
      }
      this.form = form
      this.drawer = false
    },
    onSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.title === '添加') {
            const res = await addCategory({ ...this.form })
            console.log(res)
            if (res.st === 1) {
              this.resetForm('form')
              const form = {
                pid: '',
                class_name: '',
                sort: ''
              }
              this.form = form
              this.getList()
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.drawer = false
            } else {
              console.log(res)
              this.$message.error('添加失败')
            }
          } else if (this.title === '编辑') {
            const res = await editCategory({ ...this.form })
            console.log(res)
            if (res.st === 1) {
              this.resetForm('form')
              const form = {
                class_name: '',
                pid: '',
                sort: '',
                id: ''
              }
              this.form = form
              this.getList()
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
              this.drawer = false
            } else {
              console.log(res)
              this.$message.error('编辑失败')
            }
          }
        }
      })
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = this.url + res.key
      this.form.img = this.imageUrl
    },
    beforeAvatarUpload(file) {
      //   const isJPG = file.type === "image/jpeg";
      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isLt1M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return
      }
    },
    async getToken() {
      const res = await upload()
      this.postData.token = res.data.uptoken
      this.url = res.data.domain
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.drawer = false
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-input--medium .el-input__inner {
  width: 360px;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-select-dropdown__item {
  &:first-child {
    color: #409eff;
  }
}
</style>